#include "TcpServer.h"
#include "ThreadPool.h"
#include <iostream>
using std::cout;
using std::endl;

class MyTask
{
public:
    MyTask(const string & msg,const TcpConnectionPtr & con)
    : _msg(msg)
    , _con(con)
    {}

    void process()
    {
        //如何处理数据
        _msg;

        //子线程调用process函数
        //此处如果直接将处理完的数据进行send
        //那么就是由子线程发送给客户端了
        /* _con->send(_msg); */

        //应该由子线程将处理完的数据发送给主线程
        //再由主线程发送给客户端
        _con->sendInLoop(_msg);
    }

private:
    string _msg;
    TcpConnectionPtr _con;
};

//由用户指定对三个事件的处理方式
//新的连接建立
void OnNewConnection(const TcpConnectionPtr & con)
{
    cout << con->toString() << " has connected! " << endl;
}

//客户端发送数据
void OnMessage(const TcpConnectionPtr & con, ThreadPool & pool)
{
    string msg = con->receive();
    cout << ">>recv msg from client: " << msg << endl;

    //处理接收到的数据
    //要把这个处理数据的任务传入线程池的任务队列
    //再由子线程（工作线程）取出任务来处理
    /* msg = "msg:" + msg; */

    MyTask task(msg,con);
    pool.addTask(bind(&MyTask::process,task));


    //处理后的数据发回客户端
    con->send(msg);
}


//连接断开
void OnClose(const TcpConnectionPtr & con)
{
    cout << con->toString() << " has closed! " << endl;
}


void test0(){
    TcpServer server("127.0.0.1",8888);
    server.setAllCallback(OnNewConnection,
                          OnMessage,
                          OnClose);
    server.start();
}

int main(void){
    test0();
    return 0;
}

